package com.naodong.shenluntiku.mvp.presenter;

import com.naodong.shenluntiku.mvp.contract.StudyContract;
import com.naodong.shenluntiku.mvp.model.bean.PagingBean;
import com.naodong.shenluntiku.mvp.model.bean.Study;
import com.naodong.shenluntiku.mvp.model.error.ApiError;
import com.naodong.shenluntiku.mvp.model.error.DefaultResponseErrorListener;
import com.naodong.shenluntiku.mvp.model.error.ResponseErrorListener;
import com.naodong.shenluntiku.mvp.model.error.ResultHandleSubscriber;
import com.naodong.shenluntiku.util.RxUtils;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.shingohu.man.di.scope.ActivityScope;
import me.shingohu.man.intergation.retrofit.NoBodyEntity;
import me.shingohu.man.mvp.BasePresenter;

/**
 * Created by Administrator on 2017/5/30.
 */

@ActivityScope
public class StudyPresenter extends BasePresenter<StudyContract.Model, StudyContract.View> {
    @Inject
    public StudyPresenter(StudyContract.Model model, StudyContract.View rootView) {
        super(model, rootView);
    }

    /**获取学习列表
     * @param isRefresh
     * @param url
     */
    public void requesStudyList(boolean isRefresh, String url) {
        addDisposable(mModel.getStudys(url)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (isRefresh) {
                        getView().onRequesrStart();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                    if (isRefresh) {
                        getView().onRequestFinish();
                    }
                })
                .compose(RxUtils.bindToLifecycle(getView()))
                .subscribeWith(new ResultHandleSubscriber<PagingBean<List<Study>>>(ResponseErrorListener.EMPTY) {
                    @Override
                    public void onNext(@NonNull PagingBean<List<Study>> listPagingBean) {
                        getView().setStudyListData(isRefresh, listPagingBean);
                    }
                }));
    }

    /**
     * 设置已读
     */
    public void requestSetRead(int rcId ) {

        addDisposable(mModel.setRead(rcId).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new ResultHandleSubscriber<NoBodyEntity>(new DefaultResponseErrorListener() {
            @Override
            public void handleResponseError(ApiError apiError) {
                System.out.println(123);
            }
        }) {
            @Override
            public void onNext(@NonNull NoBodyEntity noBodyEntity) {
                getView().onReadSuccess(rcId);
            }
        }));
    }
}
